#include "hdl_ap3216c.h"

int8_t hdl_ap3216c_reg_write(uint8_t reg_addr,uint8_t *w_buf,uint8_t len)
{
	return hal_i2c_write(I2C1,AP3216C_ADDRESS,reg_addr,w_buf,len);
}

int8_t hdl_ap3216c_reg_read(uint8_t reg_addr,uint8_t *r_buf,uint8_t len)
{
	return hal_i2c_read(I2C1,AP3216C_ADDRESS,reg_addr,r_buf,len);
}

unsigned char ap3216c_writeonebyte(unsigned char addr,unsigned char reg, unsigned char data)
{
    unsigned char status=0;
    unsigned char writedata=data;
    hdl_i2c_transfer_StructDef masterXfer;
	
    /* 配置I2C xfer结构体 */
   	masterXfer.slaveAddress = addr; 			/* 设备地址 				*/
    masterXfer.direction = i2c_trans_write;			/* 写入数据 				*/
    masterXfer.subaddress = reg;				/* 要写入的寄存器地址 			*/
    masterXfer.subaddressSize = 1;				/* 地址长度一个字节 			*/
    masterXfer.data = &writedata;				/* 要写入的数据 				*/
    masterXfer.dataSize = 1;  					/* 写入数据长度1个字节			*/

    if(i2c_master_transfer(I2C1, &masterXfer))
        status=1;
        
    return status;
}

/*
 * @description	: 从AP3216C读取一个字节的数据
 * @param - addr: 设备地址
 * @param - reg : 要读取的寄存器
 * @return 		: 读取到的数据。
 */
unsigned char ap3216c_readonebyte(unsigned char addr,unsigned char reg)
{
	unsigned char val=0;
	
	hdl_i2c_transfer_StructDef masterXfer;	
	masterXfer.slaveAddress = addr;				/* 设备地址 				*/
    masterXfer.direction = i2c_trans_read;			/* 读取数据 				*/
    masterXfer.subaddress = reg;				/* 要读取的寄存器地址 			*/
    masterXfer.subaddressSize = 1;				/* 地址长度一个字节 			*/
    masterXfer.data = &val;						/* 接收数据缓冲区 				*/
    masterXfer.dataSize = 1;					/* 读取数据长度1个字节			*/
	i2c_master_transfer(I2C1, &masterXfer);

	return val;
}


int8_t hdl_ap3216c_readdata(uint16_t *ir, uint16_t *ps, uint16_t *als)
{
	int8_t ret = FAIL;
    uint8_t buf[6];
	uint8_t i=0;
	for(i = 0; i < 6; i++)	
    {
        ret = hdl_ap3216c_reg_read(AP3216C_IRDATALOW + i,&buf[i],1);
    }
	if(ret == SUCCESS)
	{
		if(buf[0] & 0X80) 	/* IR_OF位为1,则数据无效 */
			*ir = 0;					
		else 				/* 读取IR传感器的数据   		*/
			*ir = ((uint16_t)buf[1] << 2) | (buf[0] & 0X03); 			

		*als = ((uint16_t)buf[3] << 8) | buf[2];	/* 读取ALS传感器的数据 			 */  

		if(buf[4] & 0x40)	/* IR_OF位为1,则数据无效 			*/
			*ps = 0;    													
		else 				/* 读取PS传感器的数据    */
			*ps = ((uint16_t)(buf[5] & 0X3F) << 4) | (buf[4] & 0X0F);
	}
	else
	{
		DBG_ERR("ap3616c read fail\r\n");
	}
	return ret;
}

int8_t hdl_ap3216_init(void)
{
	uint8_t reg_temp = 0;
	uint8_t reg_rd_temp = 0;
	reg_temp = 0x04;
	hdl_ap3216c_reg_write(AP3216C_SYSTEMCONG,&reg_temp,1);
	delayms(50);//must be
	reg_temp = 0x03;
	hdl_ap3216c_reg_write(AP3216C_SYSTEMCONG,&reg_temp,1);
	hdl_ap3216c_reg_read(AP3216C_SYSTEMCONG,&reg_rd_temp,1);
	if(reg_rd_temp == 0X03)
	{
		DBG_MSG("ap3216c init success\r\n");
		return SUCCESS;
	}
	else
	{
		DBG_ERR("ap3216c init fail\r\n");
		return FAIL;
	}
}

struct hal_ap3216c_if g_hdl_ap3216c_if = 
{
	.ap3216c_init = hdl_ap3216_init,
	.ap3216c_readdata = hdl_ap3216c_readdata,
};